const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const { formatResponse } = require('../utils/response');

// 获取分类列表
router.get('/', async (req, res) => {
  try {
    const [rows] = await pool.execute('SELECT id, name, zhushi FROM categories');
    // 按px接口格式转换数据
    const formattedData = rows.map(row => ({
      id: row.id,
      name: row.name,
      zhushi: row.zhushi, // 数据库中无对应字段，暂设为null
    }));
    res.json(formatResponse(200, '分类列表获取成功', formattedData));
  } catch (error) {
    res.status(500).json(formatResponse(500, '分类列表获取失败', error.message));
  }
});

// 获取单个分类
router.get('/:id', async (req, res) => {
  try {
    const categoryId = req.params.id;
    const [rows] = await pool.execute('SELECT * FROM categories WHERE id = ? ', [categoryId]);
    
    if (rows.length === 0) {
      return res.status(404).json(formatResponse(404, '分类不存在'));
    }
    
    res.json(formatResponse(200, '分类获取成功', rows[0]));
  } catch (error) {
    res.status(500).json(formatResponse(500, '分类获取失败', error.message)); 
  }
});

module.exports = router;